﻿Imports TNCDAL
Imports System.Data.Linq
Imports System.Linq


Public Class CAgent
    Dim db As New TanNamChinhDataContext

    Public Sub New()

    End Sub

    Public Sub New(ByVal dataContext As TanNamChinhDataContext)
        db = dataContext
    End Sub

    Public Function SelectAllRecord() As IQueryable(Of tblAgent)
        Dim agent = From p In db.tblAgents
                    Where p.IsActive = True
                    Select p
                    Order By p.Name

        Return agent
    End Function

    Public Function SelectAllRecordByName(ByVal Name As String) As IQueryable(Of tblAgent)
        Dim agent = From p In db.tblAgents
                    Where p.IsActive = True And p.Name.ToLower.Contains(Name.ToLower)
                    Select p
                    Order By p.Name

        Return agent
    End Function

    Public Function SelectRecordById(ByVal id As Integer) As tblAgent
        Dim agent = (From p In db.tblAgents
                 Where p.ID_Agent = id
                 Select p).Single
        Return agent
    End Function

#Region "Code HT"
    ''' <summary>
    ''' Lấy danh sách Agent theo Name (Name là duy nhất)
    ''' Create date: 23-12-2013
    ''' </summary>
    ''' <param name="name"></param>
    ''' <returns></returns>
    ''' <remarks></remarks>
    Public Function SelectRecordByName(ByVal name As String) As tblAgent
        Dim result = (From p In SelectAllRecord()
                 Where p.Name = name
                 Select p).Single
        Return result
    End Function
#End Region

    Public Sub Insert(ByVal obj As tblAgent)
        db.tblAgents.InsertOnSubmit(obj)
        db.SubmitChanges()
    End Sub

    Public Sub Update(ByVal obj As tblAgent)
        Dim agent = SelectRecordById(obj.ID_Agent)
        agent.Name = obj.Name
        agent.Address = obj.Address
        agent.Fax = obj.Fax
        agent.Tel = obj.Tel
        db.SubmitChanges()
    End Sub

    Public Sub Delete(ByVal id As Integer)
        Dim agent = SelectRecordById(id)
        agent.IsActive = False
        db.SubmitChanges()

        'Dim agent = SelectRecordById(id)
        'db.tblAgents.DeleteOnSubmit(agent)
        'db.SubmitChanges()
    End Sub
End Class
